package models

import (
	"database/sql"
	"time"
)

type Tag struct {
	ID        int    `json:"id"`
	TagName   string `json:"tag_name"`
	CreatedAt string `json:"created_at"`
}

// GetTagList 获取标签列表，支持分页
func GetTagList(db *sql.DB, page, pageSize int) ([]Tag, int, error) {
	// 获取总记录数
	var total int
	row := db.QueryRow("SELECT COUNT(*) FROM tags")
	if err := row.Scan(&total); err != nil {
		return nil, 0, err
	}

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 查询分页数据
	rows, err := db.Query("SELECT id, tag_name, created_at FROM tags ORDER BY id DESC LIMIT ? OFFSET ?", pageSize, offset)
	if err != nil {
		return nil, 0, err
	}
	defer rows.Close()

	var tags []Tag
	for rows.Next() {
		var tag Tag
		if err := rows.Scan(&tag.ID, &tag.TagName, &tag.CreatedAt); err != nil {
			return nil, 0, err
		}
		tags = append(tags, tag)
	}

	return tags, total, nil
}

// CheckTagExists 检查标签是否已存在
func CheckTagExists(db *sql.DB, tagName string) (bool, error) {
	var exists bool
	query := "SELECT EXISTS(SELECT 1 FROM tags WHERE tag_name = ?)"
	err := db.QueryRow(query, tagName).Scan(&exists)
	return exists, err
}

// CreateTag 创建新标签
func CreateTag(db *sql.DB, tagName string) error {
	// 检查标签是否已存在
	exists, err := CheckTagExists(db, tagName)
	if err != nil {
		return err
	}
	if exists {
		return ErrTagExists
	}

	// 插入新标签
	createdAt := time.Now().Format("2006-01-02 15:04:05")
	_, err = db.Exec("INSERT INTO tags (tag_name, created_at) VALUES (?, ?)", tagName, createdAt)
	return err
}

// ErrTagExists 标签已存在错误
var ErrTagExists = ErrRecordExists{Message: "标签已存在"}

// UpdateTag 更新标签信息
func UpdateTag(db *sql.DB, id int, tagName string) error {
	// 检查标签是否已存在
	var existingID int
	err := db.QueryRow("SELECT id FROM tags WHERE tag_name = ? AND id != ?", tagName, id).Scan(&existingID)
	if err == nil {
		return ErrTagExists
	} else if err != sql.ErrNoRows {
		return err
	}

	// 更新标签
	result, err := db.Exec("UPDATE tags SET tag_name = ? WHERE id = ?", tagName, id)
	if err != nil {
		return err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if rowsAffected == 0 {
		return sql.ErrNoRows
	}

	return nil
}

// GetAllTags 获取所有标签列表
func GetAllTags(db *sql.DB) ([]Tag, error) {
	// 查询所有标签数据
	rows, err := db.Query("SELECT id, tag_name, created_at FROM tags ORDER BY id DESC")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var tags []Tag
	for rows.Next() {
		var tag Tag
		if err := rows.Scan(&tag.ID, &tag.TagName, &tag.CreatedAt); err != nil {
			return nil, err
		}
		tags = append(tags, tag)
	}

	return tags, nil
}

// DeleteTag 删除标签
func DeleteTag(db *sql.DB, id int) error {
	// 删除标签
	result, err := db.Exec("DELETE FROM tags WHERE id = ?", id)
	if err != nil {
		return err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if rowsAffected == 0 {
		return sql.ErrNoRows
	}

	return nil
}
